package com.doubletick.proxy.ipidea.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.doubletick.proxy.ipidea.util.dto.IpIdeaResponseDto;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IpIdeaUtil {


    public static Long lastExecuteTime = System.currentTimeMillis();

    public static long intervalTime = 2005;


    @SneakyThrows
    public static IpIdeaResponseDto request(String url, Object body, String label) {
        log.info("执行 label:{} requestBody:{}", label, body);
        String requestBodyStr = JSON.toJSONString(body);
        long now = System.currentTimeMillis();
        if (now - lastExecuteTime < intervalTime) {
            long sleepTime = intervalTime - (now - lastExecuteTime);
            log.info("执行频繁, label:{} 休眠sleepTime:{}", label, sleepTime);
            Thread.sleep(sleepTime);
        }
        lastExecuteTime = System.currentTimeMillis();
        String result = HttpUtil.post(url, requestBodyStr);
        log.info("label:{} requestBody:{} result:{}", label, requestBodyStr, result);
        return JSON.to(IpIdeaResponseDto.class, result);
//        return JSON.toJavaObject(JSON.parseObject(result), IpIdeaResponseDto.class);
    }

}
